<template>
  <div :class="$style.main">
    <div :class="$style.queryContainer">
      <el-form :inline="true" :model="params">
        <el-form-item label="基地">
          <el-select @change="handleDomainChange" clearable placeholder="请选择" v-model="domainParams.domain">
            <el-option
              :key="item.value"
              :label="item.label"
              :value="item.domains"
              v-for="item in layer1">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="厂部">
          <el-select @change="handleCustomerChange" clearable placeholder="请选择" v-model="domainParams.customer">
            <el-option
              :key="item.value"
              :label="item.label"
              :value="item.domains"
              v-for="item in layer2">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产线">
          <el-select clearable placeholder="请选择" v-model="domainParams.project">
            <el-option
              :key="item.value"
              :label="item.label"
              :value="item.domains"
              v-for="item in layer3">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="任务状态">
          <dict-select v-model="params.tickeTaskStatus" dictCode="baowuSummaryStatus" />
        </el-form-item>
        <el-form-item label="报警级别">
          <dict-select v-model="params.severity" dictCode="baowualertSeverity" />
        </el-form-item>
        <el-form-item label="报警日期">
          <el-date-picker
            :picker-options="getPickerOptions()"
            align="right"
            end-placeholder="结束日期"
            range-separator="——"
            start-placeholder="开始日期"
            type="daterange"
            unlink-panels
            @change="validDate"
            v-model="params.eventDate">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button @click="queryList()" type="primary">查询</el-button>
          <el-button @click="initQueryParams()">清除</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div :class="$style.content">
      <div :class="$style.staticEchart" id="staticEchart"></div>

      <ps-table :total="dataTotal" :currentPage="paging.start/paging.length+1" @page-change="queryList">
        <el-row :class="$style.tableTop" type="flex">
          <el-col>结果详情</el-col>
          <el-col class="text-align-right">
            <el-button type="primary" @click="downloadFile()">导出</el-button>
          </el-col>
        </el-row>
        <el-table :data="tableData" size="mini" tooltip-effect="light">
          <el-table-column label="序号" type="index" width="50"></el-table-column>
          <template v-for="(col, i) in columns">
            <el-table-column :key="i" :label="col.label" v-if="col.prop == 'severity'">
              <template slot-scope="scope">
                <div v-html="priorityFormatter(scope.row.severity)"></div>
              </template>
            </el-table-column>
            <el-table-column :formatter="col.formatter" :key="i" :label="col.label" :prop="col.prop" :width="col.width" show-overflow-tooltip v-else></el-table-column>
          </template>
        </el-table>
      </ps-table>

    </div>
  </div>
</template>

<script>
import { getDomainsByFilters } from '../../../common/js/request-resource-ui-service.js';
import { exportBGExcel } from '../../../common/js/request-excel-service.js';
import moment from 'moment';
import api from './../../../common/js/api.js';
import echartsFactory from './../../../common/js/ehcarts-factory.js';
import { tickeTaskStatusFormatter, alertFromTypeFormatter, priorityFormatter } from './../../../common/js/utils.js';
import DictSelect from './../../../default/components/dict-select/DictSelect.vue';
import PsTable from './../../../default/components/table/PsTable.vue';

export default {
  data () {
    return {
      paging: {
        length: 10,
        start: 0,
        statCount: true
      },
      params: {
        tickeTaskStatus: '', // 任务状态
        domains: '',
        eventDate: [
          moment(moment().startOf('day').month(moment().month() - 2)).utc().format(),
          moment(moment().endOf('day')).utc().format()
        ],
        severity: '', // 报警级别
        ticketCategory: {
          'IN': ['50', '90', '260', '-1 ']
        }
      },
      domainParams: {
        domain: '',
        customer: '',
        project: ''
      },
      domainList: [[], [], []],
      layer1: [],
      layer2: [],
      layer3: [],
      dataTotal: 0,
      currentPage: 0,
      // index: "序号",
      tableData: [],
      tableDataTotal: 0,
      columns: [
        {
          label: '管理区域',
          prop: 'customerName',
          width: ''
        }, {
          label: '报警时间',
          prop: 'eventDate',
          width: '180',
          formatter: function (row, column, cellValue, index) {
            let rr = moment(cellValue).format('YYYY-MM-DD HH:mm:ss');
            return rr;
          }
        }, {
          label: '处理状态',
          prop: 'tickeTaskStatus',
          width: '100',
          formatter: function (r, col, val, index) {
            return tickeTaskStatusFormatter(val);
          }
        }, {
          label: '巡检人员',
          prop: 'alertConfirmPersonName',
          width: '140'
        }, {
          label: '设备名称',
          prop: 'deviceName',
          width: ''
        }, {
          label: '设备编号',
          prop: 'deviceId',
          width: '120'
        }, {
          label: '测点位置',
          prop: 'instanceName',
          width: '140'
        }, {
          label: '任务来源',
          prop: 'alertFromType',
          width: '',
          formatter: function (r, col, val, index) {
            return alertFromTypeFormatter(val);
          }
        }, {
          label: '报警信息',
          prop: 'alertTitle',
          width: ''
        }, {
          label: '报警级别',
          prop: 'severity',
          width: '',
          formatter: function (r, col, val, index) {
            return priorityFormatter(val);
          }
        }, {
          label: '故障或分析原因',
          prop: 'colseReason',
          width: '180',
          formatter: function (r, col, val, index) {
            let res = val || r.multipleConclusion || '';
            res == 'null' && (res = '');
            return res;
          }
        }, {
          label: '分析人员',
          prop: 'responsiblePersonName',
          width: ''
        }, {
          label: '状态反馈',
          prop: 'abnormalEvaluateCheckboxlist',
          width: '',
          formatter: function (r, col, val, index) {
            let res = '';
            if (r.customerName.indexOf(1580) > -1) {
              if (r.tallyEvaluateCheckboxlist == 0) {
                res = '正确';
              } else if (r.tallyEvaluateCheckboxlist == 1) {
                res = '基本正确';
              } else if (r.tallyEvaluateCheckboxlist == 2) {
                res = '不正确';
              }
            } else {
              if (r.abnormalEvaluateCheckboxlist == 0) {
                res = '有效';
              } else if (r.abnormalEvaluateCheckboxlist == 1) {
                res = '无效';
              } else {
                res = '';
              }
            }
            return res;
          }
        }, {
          label: '反馈人员',
          prop: 'evaluateUserName',
          width: ''
        }, {
          label: '备注',
          prop: 'remark',
          width: ''
        }
      ]
    };
  },
  methods: {
    priorityFormatter: priorityFormatter,
    /** 改变基地 */
    handleDomainChange: function () {
      if (!this.domainParams.domain) {
        this.initdomainList();
      } else {
        this.layer2 = this.domainList[1].filter(el => el.domains.indexOf(this.domainParams.domain || '') > -1);
        this.layer3 = [];
      }
      this.domainParams.customer = '';
      this.domainParams.project = '';
    },
    /** 改变厂部 */
    handleCustomerChange: function () {
      if (!this.domainParams.customer) {
        this.layer3 = this.domainList[2].filter(el => el);
      } else {
        this.layer3 = this.domainList[2].filter(el => el.domains.indexOf(this.domainParams.customer || '') > -1);
      }
      this.domainParams.project = '';
    },

    getPickerOptions: function () {
      let options = {
        shortcuts: [{
          text: '当日',
          onClick (picker) {
            const start = moment(moment().startOf('day')).utc().format();
            const end = moment(moment().endOf('day')).utc().format();
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '本周',
          onClick (picker) {
            const start = moment(moment().startOf('isoWeek')).utc().format();
            const end = moment(moment().endOf('isoWeek')).utc().format();
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '本月',
          onClick (picker) {
            const start = moment(moment().startOf('month')).utc().format();
            const end = moment(moment().endOf('month')).utc().format();
            picker.$emit('pick', [start, end]);
          }
        }]
      };
      return options;
    },

    validDate (dateRange) {
      let startD = moment(dateRange[0]);
      let preStartD = moment(dateRange[1]).month(moment(dateRange[1]).month() - 2);
      if (preStartD - startD > 0) {
        this.params.eventDate[0] = preStartD.utc().format();
        this.$message({type: 'warning', message: '时间跨度不能超过两个月'});
      }
    },

    init () {
      let params = {
        domains: '',
        category: 'Domain'
      };
      try {
        params.domains = this.$store.state.user.currentUser.domains;
      } catch (e) {
      }
      getDomainsByFilters(params).then(res => {
        this.initdomainList(res.data);
      });
    },

    initdomainList: function (res) {
      if (res) {
        this.layer1 = res.filter(el => { return el.modelId == '300' && el.layer == '2'; });
        this.domainList[1] = (res.filter(el => { return el.modelId == '300' && el.layer == '3'; }) || []);
        this.domainList[2] = res.filter(el => { return el.modelId == '301' && el.layer == '1'; }) || [];
        this.domainList[1].forEach(el => { el.label += `(${el.values.standardAddress})`; });
      }
      this.layer2 = this.domainList[1].filter(el => el);
      this.layer3 = this.domainList[2].filter(el => el);
    },

    formatDetailParams: function () {
      let tempParams = JSON.parse(JSON.stringify(this.params));
      if (tempParams.severity) tempParams.severity = Number(tempParams.severity);
      delete tempParams.domains;
      tempParams.customer = this.domainParams.customer;
      tempParams.project = this.domainParams.project;
      return tempParams;
    },

    /**
     * 查询列表数据
     * pageInfo：只改变了分页信息，不调用统计结果查询接口
     */
    queryList: function (pageInfo) {
      if (!pageInfo) {
        let paramsTemp = JSON.parse(JSON.stringify(this.params));
        if (paramsTemp.severity) paramsTemp.severity = Number(paramsTemp.severity);
        try {
          paramsTemp.domains = this.domainParams.domain || this.$store.state.user.currentUser.domains || '';
        } catch (e) {}
        api.post('baogangTicketService/getAlertStatistics', [paramsTemp]).then(this.updateEchart);
        this.paging.start = 1;
      } else {
        this.paging.length = pageInfo.length;
        this.paging.start = pageInfo.start;
      }

      api.post('baogangTicketService/getAlertAndDetailByPage', [this.formatDetailParams(), this.paging]).then(res => {
        this.tableData = JSON.parse(JSON.stringify(res.data.data));
        this.dataTotal = res.data.total;
      });
    },

    /** 清除 */
    initQueryParams: function () {
      Object.keys(this.domainParams).forEach(key => {
        this.domainParams[key] = '';
      });
      this.params.tickeTaskStatus = '';
      this.params.severity = '';
      this.params.eventDate = [
        moment(moment().startOf('day').month(moment().month() - 2)).utc().format(),
        moment(moment().endOf('day')).utc().format()
      ];
      this.queryList();
    },

    updateEchart ({ data: tc }) {
      let famater = {
        abnormalDealing: '异常待处理',
        alertDealing: '报警待处理',
        resultAssessing: '结果待评价',
        ending: '已完成',
        unknown: '未知状态'
      };
      let xAxisData = [];
      let yAxisData = [];
      for (let k in tc) {
        xAxisData.push(famater[k]);
        yAxisData.push(tc[k]);
      }
      let option = {
        xAxis: {
          type: 'category',
          data: xAxisData
        },
        yAxis: {
          type: 'value',
          axisLabel: {}
        },
        tooltip: {
          axisPointer: {
            type: 'shadow'
          },
          formatter: '{b}<br/>{c0}<br/>'
        },
        series: [{
          data: yAxisData,
          type: 'bar',
          cursor: 'pointer',
          barWidth: 50,
          itemStyle: {
            normal: {
              color: function (params) {
                var colorList = ['#34A9CE', '#CB9931', '#CB99CC', '#949494', '#ffffff'];
                return colorList[params.dataIndex];
              }
            }
          }
        }]
      };
      echartsFactory.getEcharts().then(echarts => {
        let myChart = echarts.init(document.getElementById('staticEchart'), 'baogang');
        myChart.setOption(option);
      });
    },

    /** 导出 */
    downloadFile: function () {
      let format = 'titles=序号,管理区域,报警时间,处理状态,巡检人员,设备名称,设备编号,测点位置,任务来源,报警信息,报警级别,故障或分析原因,分析人员,状态反馈,反馈人员,备注' +
      '&fields=customerName,eventDate,tickeTaskStatus,alertConfirmPersonName,deviceName,deviceId,instanceName,alertFromType,alertTitle,severity,' +
      'multipleConclusion,responsiblePersonName,abnormalEvaluateCheckboxlist,evaluateUserName,remark';
      exportBGExcel(
        'baogangTicketService',
        'exportAlertAndDetail',
        format,
        [this.formatDetailParams(), {start: 0, length: 99999}]
      ).then(res => {
        if (res.code == 0) {
          let url = window.location.protocol + '//' + window.location.host;
          window.open(url + res.data, '_blank');
        } else {
          this.$message({
            type: 'error',
            message: '请检查网络或查询添加后重试...'
          });
        }
      });
    }
  },
  components: {
    DictSelect,
    PsTable
  },
  mounted () {
    this.init();
    this.queryList();
  },
  activated () {
    this.init();
    this.queryList();
  }
};
</script>

<style lang="scss" module>
@import "./../../../style/default/AlarmStatisticAnalysis.scss";
</style>
